﻿using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;

namespace Learun.Application.Web.Areas.ZZDT_EC.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-02-23 11:30
    /// 描 述：属性表
    /// </summary>
    public class ec_Wire_GroupController : MvcControllerBase
    {
        private ec_Wire_GroupIBLL ec_Wire_GroupIBLL = new ec_Wire_GroupBLL();
        private ec_Wire_Group_TemplateIBLL ec_Wire_Group_TemplateIBLL = new ec_Wire_Group_TemplateBLL();

        #region 视图功能

        /// <summary>
        /// 主页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 主页面
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ProjectIndex()
        {
            return View();
        }
        /// <summary>
        /// 表单页
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Form()
        {
            return View();
        }
        /// <summary>
        /// 选择模板
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult SelectTemplate()
        {
            return View();
        }
        /// <summary>
        /// 成品导出
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExportTemplate()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取左侧树形数据
        /// <summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTree(string ProjectId)
        {
            var data = ec_Wire_GroupIBLL.GetTree(ProjectId);
            return Success(data);
        }
        /// <summary>
        /// 信号列表
        /// </summary> 
        /// <param name="projectId">项目编号</param>
        /// <param name="templateId">模板编号</param>
        /// <param name="wireGroupId">信号编号</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetList(string pagination, string queryJson)
        {
            try
            {
                Pagination paginationobj = pagination.ToObject<Pagination>();
                paginationobj.sidx = "OrderID ";
                paginationobj.sord = "ASC";
                var data = ec_Wire_GroupIBLL.GetList(queryJson, Assigned: false, pagination: paginationobj);
                var jsonData = new
                {
                    rows = data,
                    total = paginationobj.total,
                    page = paginationobj.page,
                    records = paginationobj.records
                };
                return Success(jsonData);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <param name="engineDataID">工程数据ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string queryJson)
        {
            try
            {
                var res = ec_Wire_GroupIBLL.GetList(queryJson);
                return Success(res);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            };
        }
        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <param name="engineDataID">工程数据ID</param>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string queryJson)
        {
            Pagination paginationobj = pagination.ToObject<Pagination>();
            var data = ec_Wire_GroupIBLL.GetList(queryJson, pagination: paginationobj);
            var jsonData = new
            {
                rows = data,
                total = paginationobj.total,
                page = paginationobj.page,
                records = paginationobj.records
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取表单数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetFormData(string keyValue, string ProjectId)
        {
            var data = ec_Wire_GroupIBLL.GetEntity(keyValue, ProjectId);
            var jsonData = new
            {
                ec_Wire_Group = data
            };
            return Success(jsonData);
        }
        /// <summary>
        /// 获取对象类型目录树形数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTreeData(string ProjectId, bool isShowCheck, string WireGroupTemplateID, string CurWireGroupID)
        {
            string queryJson = "{\"ProjectId\":\"" + ProjectId + "\",\"WireGroupTemplateID\":\"" + WireGroupTemplateID + "\",\"CurWireGroupID\":\"" + CurWireGroupID + "\"}";
            var list = ec_Wire_GroupIBLL.GetList(queryJson);

            List<TreeModel> treeList = new List<TreeModel>();
            foreach (var item in list)
            {
                TreeModel node = new TreeModel();
                node.id = item.Wire_Group_ID;
                node.text = item.Group_Name;
                node.value = item.Wire_Group_ID;
                node.showcheck = isShowCheck;
                node.checkstate = 0;
                node.isexpand = false;
                node.parentId = item.LinkedID;
                node.NodeExtData = item;
                treeList.Add(node);
            }
            var res = treeList.ToTree();
            return Success(res);
        }
        #endregion
        #region 提交数据
        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult DeleteForm(string keyValue, string ProjectId)
        {
            var res = ec_Wire_GroupIBLL.DeleteEntity(ProjectId, keyValue, false);
            if (string.IsNullOrEmpty(res))
            {
                return Success("删除成功！");
            }
            else
            {
                return Fail(res);
            }
        }
        /// <summary>
        /// 导入数据（网页）
        /// </summary>
        /// <param name="fileId">文件主键（导入之前会上传文件，在lr base annexesfile表中，创建一行记录。那里会得到Id）</param>
        /// <param name="ProjectId"></param>
        /// <param name="WireGroupTemplateID"></param>
        /// <param name="mode">1时为（只新增），2时为（新增和更新）,3时为（完全）</param>
        /// <param name="version">1,1462;2,8600</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult ExcelImport(string fileId, string ProjectId, string WireGroupTemplateID, ImportMode mode, int version)
        {
            try
            {
                var bll = new ec_Wire_GroupBLL(ProjectId);
                string res = "";
                switch (mode)
                {
                    case ImportMode.Create:
                        res = bll.ImportSignals(ProjectId, WireGroupTemplateID, fileId, false, version);
                        break;
                    case ImportMode.CreateUpdate:
                        res = bll.ImportSignals(ProjectId, WireGroupTemplateID, fileId, true, version);
                        break;
                    case ImportMode.Full:
                        //24 6 5新增
                        res = bll.ImportSignalsFullMode(ProjectId, WireGroupTemplateID, fileId, mode, version);
                        break;
                    default:
                        break;
                }

                if (!string.IsNullOrEmpty(res))
                {
                    return Fail(res);
                }
                return Success("导入完成");
            }
            catch (Exception e)
            {
                return Fail(e.Message);
            }
        }
        /// <summary>
        /// 导入结果
        /// </summary>
        /// <param name="fileId"></param>
        public void ImportResult(string fileId)
        {
            var file = new AnnexesFileBLL().GetByfolderIdEntity(fileId);
            if (string.IsNullOrWhiteSpace(file?.F_FilePath))
            {
                return;
            }
            FileDownHelper.DownLoad("", file.F_FilePath, $"导入结果{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
        }
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="DeleteFlg"></param>
        /// <param name="folderId"></param>
        /// <param name="reportFileName"></param>
        public void ExportToExcel(string ProjectId, bool DeleteFlg, string folderId, string reportFileName)
        {
            int version = 0;
            byte[] bytes = null;
            switch (reportFileName)
            {
                case "信号清册（1642版）":
                    version = 1;
                    break;
                case "信号清册（8600版）":
                    version = 2;
                    break;
                default:
                    bytes = System.Text.Encoding.UTF8.GetBytes("确保选择的报表名字为：信号清册（1642版）   或     信号清册（8600版）");
                    goto res1;
            }
            var BLL = new ec_Wire_GroupBLL();
            bytes = BLL.ExportSignals(ProjectId, DeleteFlg, version, folderId);
        res1:
            var stream = new MemoryStream(bytes);
            FileDownHelper.DownLoad(stream, $"成品导出{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
        }
        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveForm(string keyValue, string strEntity, string ProjectId)
        {
            ec_Wire_GroupEntity entity = strEntity.ToObject<ec_Wire_GroupEntity>();
            ec_Wire_GroupIBLL.SaveEntity(ProjectId, ref keyValue, entity);
            return Success("保存成功！");
        }
        /// <summary>
        /// 改变实体状态
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult SaveStatus(string ProjectId, string keyValue, WireGroupStatusEnum status)
        {
            var tableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(ProjectId);
            var entity = SqlSugarHelper.Db.Queryable<ec_Wire_GroupEntity>().AS(tableName).First(x => x.Wire_Group_ID == keyValue);
            if (entity == null)
            {
                return Fail("信号不存在！！！");
            }
            entity.Status = status;
            var BLL = new ec_Wire_GroupBLL(ProjectId);
            string result = BLL.SaveEntity(ProjectId, ref keyValue, entity, "0");
            if (string.IsNullOrEmpty(result))
            {
                return Success("修改成功！");
            }
            else
            {
                return Fail(result);
            }
        }
        #endregion
    }
}
